﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using POSSystem.BLL;
using MyGeneration.dOOdads;
using WebUI.Controls;

namespace WebUI
{
    public partial class VoucherManagement : BasePage
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            base.Page_Load(sender, e);
            gridVoucher.OnNeedDataSource = gridVoucher_OnNeedDataSource;

            if (!IsPostBack)
            {
                ExpirationDate = DateTime.UtcNow.AddHours(SysVars.TimeZone);
                gridVoucher.Refresh();
            }

            
        }

        protected void gridVoucher_OnProductNameClick(object sender, EventArgs e)
        {
            Guid id = new Guid(gridVoucher.SelectedValue);
            View_Vouchers vc = View_Vouchers.GetById(id);
            PrintVoucher(vc);
        }

        protected void btnRemoveVoucher_OnClick(object sender, EventArgs e)
        {
            gridVoucher.DeleteCheckedItems();
            gridVoucher.Refresh();
        }

        protected void btnPrintVoucher_OnClick(object sender, EventArgs e)
        {
            View_Vouchers vc = new View_Vouchers();
            string filter = GetFilter();
            int totalRow = vc.Search(filter, "*", View_Vouchers.ColumnNames.Code + " ASC", 0, 99999);
            PrintVoucher(vc);
        }

        protected void btnCreate_OnClick(object sender, EventArgs e)
        {
            TransactionMgr tx = TransactionMgr.ThreadTransactionMgr();
            try
            {
                tx.BeginTransaction();
                VoucherSeries series = new VoucherSeries();
                series.AddNew();
                series.ID = Guid.NewGuid();
                series.Name = txtName.Text;
                series.ExpirationDate = ExpirationDate.AddDays(1).AddSeconds(-1);
                series.CreatedDate = DateTime.UtcNow.AddHours(SysVars.TimeZone);
                series.Count = int.Parse(txtQuantity.Text);
                series.LastModifiedByUser = SessionUser.ID;
                series.MultiCheckOut = rdMulti.Checked;
                series.Deleted = false;
                if (rdAmount.Checked)
                    series.DiscountAmount = decimal.Parse(txtDisAmount.Text);
                else
                    series.DiscountPercent = int.Parse(txtDiscountPer.Text);

                series.Save();

                Vouchers vc = new Vouchers();
                Dictionary<string, string> dict = new Dictionary<string, string>();
                for (int i = 0; i < series.Count; i++)
                {
                    string key = "";
                    Guid id = Guid.Empty;
                    while (dict.ContainsKey(key) || key == "")
                    {
                        id =  Guid.NewGuid();
                        key = id.ToString().Replace("-", "").Substring(0, 13);
                    }

                    dict[key] = string.Format("{0}{1}{2}", series.CreatedDate.Month.ToString().PadLeft(2, '0'), series.CreatedDate.Year.ToString().Substring(2, 2), key);
                    vc.AddNew();
                    vc.ID = id;
                    vc.Code = dict[key];
                    vc.IsUsed = false;
                    vc.SerieID = series.ID;
                    vc.Deleted = false;
                    vc.Active = true;
                    if (rdAmount.Checked)
                        vc.Balance = series.DiscountAmount;
                }

                vc.Save();

                tx.CommitTransaction();

                ShowHintMessage(panelLLookUp, "Vouchers have been created successfully!");
                if (chkPrint.Checked)
                {
                    PrintVoucher(View_Vouchers.GetBySerieId(vc.SerieID));
                }

            }
            catch (Exception ex)
            {
                tx.RollbackTransaction();
                ErrorLog.WriteToFile("VoucherManagement.aspx.cs", "btnCreate_OnClick", ex.StackTrace + ex.Message);
                ShowErrorMessage(panelLLookUp, "Error in creating vouchers: " + ex.Message);
            }
        }

        public string PrintKey
        {
            get
            {
                if (ViewState["PrintKey"] == null)
                    ViewState["PrintKey"] = Guid.NewGuid().ToString();
                return ViewState["PrintKey"].ToString();
            }
        }

        public string GetPrintPage()
        {
            return "EditPages/PrintHandler.aspx?key=" + PrintKey;
        }

        protected void PrintVoucher(View_Vouchers vc)
        {
            PrintVouchertListCtrl printedList = (PrintVouchertListCtrl)LoadControl(@"~/Controls/POSControls/PrintVoucherListCtrl.ascx");
            printedList.SourceObject = vc;
            printedList.AllowPaging = false;
            printedList.AllowSelecting = false;
            printedList.AllowSorting = false;
            printedList.ShowFooter = false;
            printedList.ShowHeader = false;
            printedList.GridBorder = BorderStyle.None;
            printedList.GridLineStyle = GridLines.None;
            printedList.Refresh();
            Session[PrintKey] = printedList;
            ScriptManager.RegisterClientScriptBlock(this, typeof(Page), Guid.NewGuid().ToString(), String.Format("showPrintDlg('{0}');", GetPrintPage()), true);

        }

        DateTime ExpirationDate
        {
            get
            {
                if (txtExpirationDate.Text == "")
                    txtExpirationDate.Text = DateTime.UtcNow.AddHours(SysVars.TimeZone).ToString(calExpirationDate.Format);
                return DateTime.ParseExact(txtExpirationDate.Text, calExpirationDate.Format, null);
            }
            set { txtExpirationDate.Text = value.ToString(calExpirationDate.Format); }
        }

        protected void btnClear_OnClick(object sender, EventArgs e)
        {
            txtDisAmount.Text = "0";
            txtDiscountPer.Text = "0";
            ExpirationDate = DateTime.UtcNow.AddHours(SysVars.TimeZone);
            txtName.Text = "";
            txtQuantity.Text = "0";
        }

        protected void btnLookup_OnClick(object sender, EventArgs e)
        {
            gridVoucher.CurrentPageIndex = 0;
            gridVoucher.Refresh();
        }

        protected void gridVoucher_OnNeedDataSource(object sender, EventArgs e)
        {
            View_Vouchers vc = new View_Vouchers();
            string filter = GetFilter();
            string sort = (gridVoucher.SortExpression + " " + gridVoucher.SortDirection).Trim();
            if (sort == "")
                sort = View_Vouchers.ColumnNames.Code + " ASC";
            int totalRow = vc.Search(filter, "*", sort, gridVoucher.CurrentPageIndex * gridVoucher.PageSize, gridVoucher.PageSize);
            gridVoucher.VirtualItemCount = totalRow;
            gridVoucher.DataSource = vc.DefaultView;
        }

        private string GetFilter()
        {
            string filter = "(" + View_Vouchers.ColumnNames.Code + " LIKE '%" + txtVoucherCode.Text + "%' OR " + View_Vouchers.ColumnNames.Name + " LIKE '%" + txtVoucherCode.Text + "%')";
            if (ddlEnable.SelectedValue != "")
                filter += " AND " + View_Vouchers.ColumnNames.Active + "=" + ddlEnable.SelectedValue;
            if (ddlIsUsed.SelectedValue != "")
                filter += " AND " + View_Vouchers.ColumnNames.IsUsed + "=" + ddlIsUsed.SelectedValue;
            if (ddlExpired.SelectedValue == "1")
                filter += " AND " + View_Vouchers.ColumnNames.ExpirationDate + " < '" + DateTime.UtcNow.AddHours(SysVars.TimeZone).ToString("yyyy/MM/dd hh:mm:ss") + "'";
            else if (ddlExpired.SelectedValue == "2")
                filter += " AND " + View_Vouchers.ColumnNames.ExpirationDate + " >= '" + DateTime.UtcNow.AddHours(SysVars.TimeZone).ToString("yyyy/MM/dd hh:mm:ss") + "'";
            return filter;
        }
    }
}